import type { Ref } from 'vue'
import { ref } from 'vue'

type ISettingData = Record<string, any>

export class Setting<T extends ISettingData> {

    originalData: T

    constructor(
        public data: Ref<T>
    ) {
        this.originalData = { ...data.value }
    }

    get<K extends keyof T>(k: K) {
        return this.data.value[k]
    }

    set<K extends keyof T>(k: K, v: any) {
        this.data.value[k] = v
    }

    put(data: Partial<T>) {
        this.data.value = Object.assign(this.data.value, data)
    }

    getAll() {
        return this.data.value
    }

    reset() {
        this.data.value = { ...this.originalData }
    }
}

export function useSetting<T extends ISettingData>(data: T): Setting<T> {
    return new Setting(ref(data))
}
